<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>订单数据验证工具</title>
  <style>
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
      max-width: 1000px;
      margin: 0 auto;
      padding: 20px;
      color: #333;
    }
    h1 {
      color: #2c3e50;
      margin-bottom: 20px;
    }
    .container {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 20px;
    }
    .card {
      background-color: #fff;
      border: 1px solid #e0e0e0;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    h2 {
      color: #34495e;
      margin-top: 0;
      margin-bottom: 15px;
      font-size: 18px;
      border-bottom: 1px solid #eee;
      padding-bottom: 10px;
    }
    pre {
      background-color: #f8f9fa;
      padding: 15px;
      border-radius: 4px;
      overflow-x: auto;
      font-size: 14px;
      line-height: 1.5;
      max-height: 400px;
    }
    .success {
      color: #27ae60;
    }
    .error {
      color: #e74c3c;
    }
    .info {
      color: #3498db;
    }
    .button {
      background-color: #3498db;
      color: white;
      border: none;
      padding: 10px 15px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      margin-bottom: 15px;
    }
    .button:hover {
      background-color: #2980b9;
    }
    .loading {
      display: none;
      padding: 10px;
      text-align: center;
      background-color: #fff3cd;
      border-radius: 4px;
    }
    .summary {
      font-size: 16px;
      margin-bottom: 10px;
    }
    .highlight {
      background-color: #fff3cd;
      padding: 2px 4px;
      border-radius: 3px;
    }
  </style>
</head>
<body>
  <h1>订单数据验证工具</h1>
  
  <div class="summary">
    此工具用于直接测试订单API接口并验证数据加载和处理情况。
    <br><br>
    <strong>重要修复：</strong> 已将前端代码中的数据结构从 <span class="highlight">data.records</span> 修正为 <span class="highlight">data.list</span>，以匹配后端实际返回的数据结构。
  </div>
  
  <button class="button" onclick="testOrderAPI()">测试订单API</button>
  
  <div class="loading" id="loading">加载中...</div>
  
  <div class="container">
    <div class="card">
      <h2>API响应数据</h2>
      <pre id="response-data">(点击上方按钮开始测试)</pre>
    </div>
    
    <div class="card">
      <h2>订单数据处理结果</h2>
      <pre id="processed-data">(点击上方按钮开始测试)</pre>
    </div>
  </div>
  
  <div class="card" style="margin-top: 20px;">
    <h2>验证结果</h2>
    <div id="validation-result">
      <p>请点击上方按钮进行测试。</p>
    </div>
  </div>

  <script>
    // 模拟前端数据处理逻辑
    function getStatusString(statusNumber) {
      const statusMap = {
        1: 'pending',     // 待付款
        2: 'paid',        // 已付款
        3: 'shipped',     // 已发货
        4: 'delivered',   // 已收货
        5: 'completed',   // 已完成
        6: 'cancelled',   // 已取消
        7: 'refunded'     // 已退款
      };
      return statusMap[statusNumber] || 'unknown';
    }

    function formatDate(dateString) {
      if (!dateString) return '';
      try {
        const date = new Date(dateString);
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        });
      } catch (e) {
        return dateString;
      }
    }

    function formatOrderItems(order) {
      // 简化的商品数据格式化逻辑
      if (!order) return [];
      
      // 由于API返回的订单数据中没有详细的items数组，我们根据productCount生成模拟数据
      const productCount = order.productCount || 0;
      const items = [];
      
      for (let i = 0; i < productCount; i++) {
        items.push({
          id: `item_${order.orderNo}_${i}`,
          productName: order.firstProductName || '商品名称',
          price: (order.totalAmount / productCount) || 0,
          quantity: 1,
          productImage: `https://picsum.photos/id/${i + 10}/80/80`
        });
      }
      
      return items;
    }

    async function testOrderAPI() {
      const loading = document.getElementById('loading');
      const responseData = document.getElementById('response-data');
      const processedData = document.getElementById('processed-data');
      const validationResult = document.getElementById('validation-result');
      
      // 显示加载状态
      loading.style.display = 'block';
      responseData.textContent = '加载中...';
      processedData.textContent = '加载中...';
      validationResult.innerHTML = '<p>正在请求订单数据...</p>';
      
      try {
        // 从localStorage获取token
        const token = localStorage.getItem('token');
        
        // 设置请求头
        const headers = {
          'Content-Type': 'application/json'
        };
        
        if (token) {
          headers['Authorization'] = `Bearer ${token}`;
        }
        
        // 发送请求
        const response = await fetch('/order/list', {
          method: 'GET',
          headers: headers,
          credentials: 'include'
        });
        
        if (!response.ok) {
          throw new Error(`HTTP错误! 状态码: ${response.status}`);
        }
        
        const data = await response.json();
        
        // 显示原始响应数据
        responseData.textContent = JSON.stringify(data, null, 2);
        
        // 处理订单数据
        let orders = [];
        let resultMessage = '';
        
        if (data?.code === 200 && data.data?.list && Array.isArray(data.data.list)) {
          // 转换订单数据
          orders = data.data.list.map(order => {
            const orderId = order.id || order.orderNo || `order_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
            const orderStatus = order.orderStatus || order.status || 1;
            const statusStr = getStatusString(orderStatus);
            
            return {
              id: orderId,
              orderNo: order.orderNo || `NO_${orderId}`,
              status: statusStr,
              statusText: order.orderStatusDesc || '未知状态',
              totalAmount: order.totalAmount || order.amount || 0,
              createTime: formatDate(order.createTime || order.createdAt),
              items: formatOrderItems(order)
            };
          });
          
          resultMessage = `
            <p class="success">✅ 数据结构验证成功！</p>
            <p>• 成功加载 ${orders.length} 条订单数据</p>
            <p>• 数据结构已修正为 <strong>data.list</strong></p>
            <p>• 订单状态转换正常</p>
          `;
        } else {
          resultMessage = `
            <p class="error">❌ 数据结构验证失败！</p>
            <p>• 响应代码: ${data?.code}</p>
            <p>• 数据字段: ${data?.data ? '存在' : '不存在'}</p>
            <p>• 列表字段: ${data?.data?.list ? '存在' : '不存在'}</p>
          `;
        }
        
        // 显示处理后的订单数据
        processedData.textContent = JSON.stringify(orders, null, 2);
        
        // 显示验证结果
        validationResult.innerHTML = resultMessage;
        
      } catch (error) {
        responseData.textContent = `请求失败: ${error.message}`;
        processedData.textContent = `处理失败: ${error.message}`;
        validationResult.innerHTML = `
          <p class="error">❌ 请求失败！</p>
          <p>${error.message}</p>
          <p class="info">提示: 请确保后端服务器已启动，并且订单接口可用。</p>
        `;
      } finally {
        // 隐藏加载状态
        loading.style.display = 'none';
      }
    }
  </script>
</body>
</html>